package com.milkshopbackend.milkshop.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.milkshopbackend.milkshop.Service.OrderService;
import com.milkshopbackend.milkshop.Service.ScheduledTaskService;
import com.milkshopbackend.milkshop.entity.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class OrderAutoCloseTask {

    @Autowired
    private OrderService orderService;

    @Autowired
    private ScheduledTaskService scheduledTaskService;

    private static final String TASK_KEY = "ORDER_AUTO_CLOSE";

    @Scheduled(cron = "0 */30 * * * ?") // 每30分钟执行一次
    public void closeTimeoutOrders() {
        log.info("Start executing order auto close task...");
        try {
            // 更新任务状态为执行中
            scheduledTaskService.updateTaskStatus(TASK_KEY, 1, null);

            // 获取超时未支付的订单（超过30分钟未支付）
            LocalDateTime timeout = LocalDateTime.now().minusMinutes(30);
            LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Order::getStatus, 0) // 待支付状态
                    .lt(Order::getCreateTime, timeout);
            List<Order> orders = orderService.list(wrapper);

            // 关闭超时订单
            for (Order order : orders) {
                try {
                    orderService.cancelOrder(order.getId(), "订单超时自动取消");
                    log.info("Auto closed timeout order: {}", order.getOrderNo());
                } catch (Exception e) {
                    log.error("Failed to auto close order: {}", order.getOrderNo(), e);
                }
            }

            // 更新任务状态为执行成功
            scheduledTaskService.updateTaskStatus(TASK_KEY, 2, null);
            log.info("Order auto close task completed. Processed {} orders", orders.size());
        } catch (Exception e) {
            log.error("Order auto close task failed", e);
            // 更新任务状态为执行失败
            scheduledTaskService.updateTaskStatus(TASK_KEY, 3, e.getMessage());
        }
    }

    // 初始化定时任务记录
    @PostConstruct
    public void init() {
        try {
            scheduledTaskService.createTask(
                    "订单自动关闭任务",
                    TASK_KEY,
                    "自动关闭超过30分钟未支付的订单",
                    "0 */30 * * * ?"
            );
        } catch (Exception e) {
            log.error("Failed to initialize order auto close task", e);
        }
    }
}